import logging

from flask import redirect
from flask_classy import FlaskView, route

from ..services.trade import TradeService

logger = logging.getLogger(__name__)
from flask import abort, request
from urllib.parse import urlencode


class GatewayCallbackView(FlaskView):
    @route('/verify/<result_id>')
    def verify(self, result_id):
        logger.info('接收到 [{}] 流水的支付反馈信息. 处理开始')

        gateway_order_result = TradeService.get_gateway_order_result(result_id)

        if not gateway_order_result:
            logger.warn('找不到[{}]的支付流水', result_id)
            abort(500)
        TradeService.verify_order_result(gateway_order_result, request.values.to_dict())
        return_url = TradeService.get_payment_result_return_url(result_id)
        if return_url:
            data = {
                'trade_code': gateway_order_result.order_no,
                'amount': gateway_order_result.amount,
                'status': gateway_order_result.status,
            }
            return_url = return_url.format(data)

            return  redirect(return_url + '?' + urlencode(data))
        else:
            return 'success'
        pass

    @route('/notify/<result_id>')
    def notify(self, result_id):
        logger.info('接收到 [{}] 流水的支付通知信息. 处理开始')

        gateway_order_result = TradeService.get_gateway_order_result(result_id)

        if not gateway_order_result:
            logger.warn('找不到[{}]的支付流水', result_id)
            abort(500)
        TradeService.verify_order_result(gateway_order_result, request.values.to_dict())
        return 'success'
